package cn.aigoubuy.service.impl;

import cn.aigoubuy.dao.OrderDao;
import cn.aigoubuy.dao.ilpl.OrderDaoImpl;
import cn.aigoubuy.domain.Order;
import cn.aigoubuy.domain.OrderItem;
import cn.aigoubuy.domain.PageBean;
import cn.aigoubuy.domain.User;
import cn.aigoubuy.service.OrderService;
import cn.aigoubuy.utils.JDBCUtils;
import org.apache.commons.dbutils.DbUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
* 订单service 实现类
*/
public class OrderServiceImpl implements OrderService {
    OrderDao orderDao=new OrderDaoImpl();
    /**
     * 业务层保存订单的方法
     * @param order
     * @throws SQLException
     */
    @Override
    public void saveOrder(Order order) throws SQLException {
        // 获得 Connection
        Connection connection = JDBCUtils.getConnection();
        try {
            // 调用OrderDao
            orderDao.saveOrder(connection,order);
            //保存订单项
            for (OrderItem item : order.getList()) {
                orderDao.saveOrderItem(connection,item);
            }
            //提交事务
            DbUtils.commitAndCloseQuietly(connection);
        }catch (Exception e) {
            DbUtils.rollbackAndCloseQuietly(connection);
        }
    }

    @Override
    public PageBean<Order> findByUid(User user, int pageNum, int pageSize) throws Exception {
        // 1.查询总记录数
        int totalRecord = orderDao.findTotalRecordByUid(user);
        // 2.封装数据
        PageBean<Order> pageBean = new PageBean<>(pageNum,totalRecord,pageSize);
        //设置url
        pageBean.setUrl("orderServlet?method=findByUid");
        // 3.分页数据
        List<Order> data = orderDao.findAllByUid(user,pageBean.getStartIndex(),pageBean.getPageSize());
        pageBean.setList(data);
        return pageBean;
    }

    @Override
    public Order findByOid(String oid) throws Exception{
        return orderDao.findByOid(oid);
    }

    @Override
    public void update(Order order) throws Exception {
        orderDao.update(order);
    }
}